<template>
	<view class="page-container">
		<view class="top-wrap">
			<view class="top-row flex-jc">
				<view class="text flex-ac" @click="handleClick">
					<view class="name">{{ model.store.storeName }}</view>
					<up-icon name="arrow-down-fill" color="#B98A73" size="10"></up-icon>
				</view>
				<view class="text flex-ac" @click="handleModelClick">
					<view class="name">{{ model.model.modelName }}</view>
					<up-icon name="arrow-down-fill" color="#000" size="10"></up-icon>
				</view>
				<view class="text flex-ac" @click="model.showDatePopup = true">
					<view class="name">{{ common.formatTimestamp(selectDate) }}</view>
					<up-icon name="arrow-down-fill" color="#B98A73" size="10"></up-icon>
				</view>
				<view :class="['text', 'flex-ac', model.showSearch ? 'active' : '']">
					<up-search shape="round" @focus="searchFocus" :animation="true" :showAction="false"
						:inputStyle="{ borderRadio: '16rpx' }" placeholder="车牌号"></up-search>
				</view>
			</view>
			<view class="top-row flex-ac">
				<view class="" v-for="(item, index) in useStatus" :key="item.name">
					<text :style="{ [0 ? 'background-image' : 'background']: item.color, }" class="tag-color"></text>
					<text>{{ item.name }}</text>
				</view>
			</view>
			<view class="top-row flex-ac">
				<view>
					车型数:{{ list.length }}
				</view>
				<view>
					车牌数:{{ list.length }}
				</view>
			</view>
		</view>
		<scroll-view class="inventory-list" scroll-x>
			<view class="scroll-row flex-ac">
				<view class="fixed-left">车型/车牌</view>
				<view class="scroll-list flex-ac">
					<view v-for="date in dateList" class="scroll-item">
						{{ date.date }}{{ date.weekday }}
					</view>
				</view>
			</view>
			<view class="scroll-content-row">
				<view v-for="item in list" class="list-item">
					<view class="flex-jc model-name">
						<view>{{ item.seriesName }}{{ item.modelName }}</view>
						<up-button type="primary" color="#986C5D" shape="circle" size="mini" plain text="调价"
							@click="changePrice"></up-button>
					</view>
					<view class="scroll-row flex-ac">
						<view class="fixed-left">{{ item.vehiclePlate }}</view>
						<view class="scroll-list flex-ac">
							<view v-for="date in dateList" class="scroll-item" @click="dayClick(item, date)"></view>
							<view v-for="order in item.vehicleOrderList" @click="orderClick(item, order)"
								:style="{ left: calcLeftOffset(order.lockStartTime, dateList[0].day) + 'px', width: calcLockPixel(order.lockStartTime, order.lockEndTime, 55) + 'px' }"
								:class="['scroll-block', 'bg-' + order.inventoryType]"></view>
						</view>
					</view>
				</view>
				<up-empty mode="list" v-if="list.length === 0" marginTop="100px" style="width: 100vw;"></up-empty>
			</view>

		</scroll-view>
		<view class="position">今</view>


		<CustomPopup :list="model.storeList" :pro="{ key: 'storeName', value: 'uuid' }" title="门店" ref="storePopupRef"
			@select="handleSelectStore"></CustomPopup>

		<CustomPopup :list="model.modelList" :pro="{ key: 'modelName', value: 'modelUuid' }" title="车型"
			ref="modelPopupRef" @select="handleSelectModel"></CustomPopup>
		<up-datetime-picker @cancel="model.showDatePopup = false" @confirm="handleConfirm" :show="model.showDatePopup"
			v-model="selectDate" mode="date" closeOnClickOverlay></up-datetime-picker>
		<ClosePopup title="车辆占库" ref="useClosePopupRef">
			<view class="close-popup-content">
				<view class="title">
					<text>{{ model.currentData.vehiclePlate }} ·</text> <text class="theme-color">已上架</text>
				</view>
				<view class="vehicle-info">{{ model.currentData.seriesName }}{{ model.currentData.modelName }}</view>
				<up-form borderBottom :labelWidth="80">
					<up-form-item label="占库类型">
						<view @click="show = true">{{ inventoryTypeMap.get(form.inventoryType) }}</view>
					</up-form-item>
					<up-form-item label="开始时间">
						<view @click="showDate(1)">{{ form.lockStartTime || '请选择开始时间' }}</view>
					</up-form-item>
					<up-form-item label="结束时间">
						<view @click="showDate(2)">{{ form.lockEndTime || '请选择结束时间' }}</view>
					</up-form-item>
				</up-form>
				<view class="flex-jc popup-btn-group">
					<up-button type="primary" color="#D9D9D9" shape="circle" text="取消" @click="cancel"></up-button>
					<up-button type="primary" color="#B98A73" shape="circle" text="确定占用"
						@click="confirmUse"></up-button>
				</view>
			</view>
		</ClosePopup>

		<ClosePopup title="释放占用" ref="cancelUseClosePopupRef" height="38vh">
			<view class="close-popup-content">
				<view class="title">
					<text>{{ model.currentData.vehiclePlate }} ·</text> <text class="theme-color">已上架</text>
				</view>
				<view class="vehicle-info">{{ model.currentData.seriesName }}{{ model.currentData.modelName }}</view>
				<view class="mt20 font20">
					占用时间：{{ model.currentData.lockStartTime }} - {{ model.currentData.lockEndTime }}
				</view>
				<view class="mt20 font20">创建时间：{{ model.currentData.order?.createTime }}</view>
				<view class="flex-jc popup-btn-group">
					<up-button type="primary" color="#D9D9D9" shape="circle" text="取消" @click="cancel"></up-button>
					<up-button type="primary" color="#B98A73" shape="circle" text="确定释放" @click="cancelUse"></up-button>
				</view>
			</view>
		</ClosePopup>
		<DateTimePicker ref="datePopupRef" @select="getDate"></DateTimePicker>
		<up-picker :show="show" :columns="columns" closeOnClickOverlay @confirm="confirm"
			@cancel="show = false"></up-picker>
	</view>
</template>

<script setup>
import {
	reactive,
	ref
} from 'vue';
import { postRequest } from "@/reuqest/request.js";
import CustomPopup from "@/components/custom-popup/index.vue";
import DateTimePicker from "@/components/dateTimePicker/index.vue";

import ClosePopup from "@/components/close-popup/index.vue";
import { inventoryTypeMap } from "@/utils/constans.js";
import common from "@/utils/common.js";
import { computed } from 'vue';
import { onMounted } from 'vue';

const storePopupRef = ref(null)
const modelPopupRef = ref(null)
const useClosePopupRef = ref(null)
const cancelUseClosePopupRef = ref(null)
const datePopupRef = ref(null)

const show = ref(false)
const columns = reactive([[...inventoryTypeMap.values()]]);

console.log(columns)

const model = reactive({
	showStorePopup: false,
	showModelPopup: false,
	showDatePopup: false,
	showSearch: false,
	store: {},
	model: { modelName: "全部车型", modelUuid: "ALL" },
	storeList: [],
	modelList: [],
	currentData: {},
	selectIndex: "",
})

const form = reactive({
	inventoryType: 2,
	lockStartTime: "",
	lockEndTime: "",
})

const list = ref([])

const selectDate = ref(Date.now());
const useStatus = ref([
	{
		color: "#FEDFCC",
		name: "订单占用"
	},
	{
		color: "#D6DCFB",
		name: "其他占用"
	},
	{
		color: "repeating-linear-gradient( -45deg, #FFDDC3, #ffffff 3px, #FFDDC3 3px, #fff 3px )",
		name: "整备占用(跟随订单占用)"
	},
	{
		color: "#FB9791",
		name: "重复占用"
	},
	// {
	// 	color: "#ad292c",
	// 	name: "微信小程序"
	// },
	// {
	// 	color: "#909399",
	// 	name: "平台录入"
	// },
	// {
	// 	color: "#eccc00",
	// 	name: "飞猪"
	// },
	// {
	// 	color: "#0086f6",
	// 	name: "携程"
	// },
])

const showDate = (type) => {
	model.currentDateType = type;
	datePopupRef.value?.open()
}

const getDate = (date) => {
	if (model.currentDateType == 1) {
		form.lockStartTime = date;
	} else {
		form.lockEndTime = date;
	}
}

const confirm = (e) => {
	console.log('confirm', e);
	for (let item of inventoryTypeMap.entries()) {
		console.log(item[0], item[1]);
		if (item[1] === e.value[0]) {
			form.inventoryType = item[0]
			break;
		}
	}
	show.value = false;
};

const handleSelectStore = (item) => {
	model.store = item
	getData()
}

const handleSelectModel = (item) => {
	model.model = item
	getData()
}

const handleClick = () => {
	storePopupRef.value?.open()
}


const cancel = () => {
	useClosePopupRef.value?.close();
	cancelUseClosePopupRef.value?.close();
}

const confirmUse = () => {
	if (!form.lockStartTime) {
		uni.$u.toast('请选择开始时间!');
		return;
	}
	if (!form.lockEndTime) {
		uni.$u.toast('请选择结束时间!');
		return;
	}
	postRequest("/wx-operation/api/v1/bm/inventory/lock", {
		inventoryType: form.inventoryType,
		lockStartTime: form.lockStartTime + ":00",
		lockEndTime: form.lockEndTime + ":00",
		vin: model.currentData.vin
	}).then(res => {
		useClosePopupRef.value?.close();
		if (res.bizCode === "00000") {
			console.log(res.data)
			if (res.data) {
				uni.$u.toast('占用成功');
				getData()
			}
		}
	})
}

const cancelUse = () => {
	postRequest("/wx-operation/api/v1/bm/inventory/unlock", {
		lockStartTime: model.currentData.lockStartTime,
		lockEndTime: model.currentData.lockEndTime,
		vin: model.currentData.vin
	}).then(res => {
		if (res.bizCode === "00000") {
			console.log(res.data)
			// model.storeList = res.data?.list || [];
			// model.store = model.storeList[0] || {};
			// getModel()
			// getData()
		}
	})
}

const dayClick = (item) => {
	console.log(item)
	model.currentData = item
	useClosePopupRef.value?.open()
}

const orderClick = (item, order) => {
	model.currentData = { ...order, vehiclePlate: item.vehiclePlate }
	console.log(model.currentData)
	cancelUseClosePopupRef.value?.open()
}

const handleModelClick = () => {
	modelPopupRef.value?.open()
}

const handleConfirm = (date) => {
	model.showDatePopup = false;
	getData()
}

const changePrice = () => {
	uni.navigateTo({
		url: "/pages/priceManage/goodsDetail"
	})
}

const calcLockPixel = (startStr, endStr, cellWidth = 55) => {
	const start = new Date(startStr)
	const end = new Date(endStr)
	const oneDayMs = 24 * 60 * 60 * 1000
	const diffMs = end - start
	return (diffMs / oneDayMs) * cellWidth
}


const calcLeftOffset = (startTimeStr, listStartDateStr, cellWidth = 55) => {
	const start = new Date(startTimeStr)
	const listStart = new Date(listStartDateStr + " 00:00:00")
	const oneDayMs = 24 * 60 * 60 * 1000
	const diffMs = start - listStart
	return (diffMs / oneDayMs) * cellWidth
}

const getNextMonthTime = (dateStr) => {
	const date = new Date(dateStr.replace(/-/g, '/')) // 兼容 iOS
	const nextMonth = new Date(date)
	nextMonth.setMonth(date.getMonth() + 1)
	const pad = (n) => n.toString().padStart(2, '0')
	const Y = nextMonth.getFullYear()
	const M = pad(nextMonth.getMonth() + 1)
	const D = pad(nextMonth.getDate())
	return `${Y}-${M}-${D}`
}

const dateList = computed(() => {

	if (selectDate.value) {
		common.formatTimestamp(selectDate.value)
		const startDate = common.formatTimestamp(selectDate.value)
		const endDate = getNextMonthTime(startDate)
		return getDateRangeWithWeekdays(startDate, endDate)
	}
	return []
})


const getDateRangeWithWeekdays = (startDate, endDate) => {
	const result = []
	const weekMap = ['日', '一', '二', '三', '四', '五', '六']

	let current = new Date(startDate.replace(/-/g, '/'))
	const end = new Date(endDate.replace(/-/g, '/'))

	while (current <= end) {
		const year = current.getFullYear()
		const month = String(current.getMonth() + 1).padStart(2, '0')
		const day = String(current.getDate()).padStart(2, '0')
		const weekday = weekMap[current.getDay()]

		result.push({
			day: `${year}-${month}-${day}`,
			weekday,
			date: `${month}/${day}`
		})

		current.setDate(current.getDate() + 1)
	}

	return result
}

const getData = () => {
	postRequest("/wx-operation/api/v1/bm/inventory/listDetail", {
		storeUuid: model.store.uuid,
		modelUuid: model.model.modelUuid,
		startDate: common.formatTimestamp(selectDate.value),
		endDate: getNextMonthTime(common.formatTimestamp(selectDate.value)),
	}).then(res => {
		if (res.bizCode === "00000") {
			console.log(res.data, dateList.value)
			list.value = res.data || [];
		}
	})

	// postRequest("/wx-operation/api/v1/bm/inventory/listOverview", {
	// 	storeUuid: model.store.uuid,
	// 	modelUuid: model.model.modelUuid,
	// 	startDate: common.formatTimestamp(selectDate.value),
	// 	endDate: getNextMonthTime(common.formatTimestamp(selectDate.value)),
	// }).then(res => {
	// 	if (res.bizCode === "00000") {
	// 		console.log(res.data)
	// 	}
	// })
}

const getModel = () => {
	postRequest("/wx-operation/api/v1/bm/vehicle/model/page", {
		pageNum: 1,
		pageSize: 2000,
		storeUuid: model.store.uuid,
	}).then(res => {
		if (res.bizCode === "00000") {
			console.log(res.data)
			model.modelList = res.data?.list || [];
		}
	})

}

const getStore = () => {
	postRequest("/wx-operation/api/v1/bm/store/page", {
		pageNum: 1,
		pageSize: 2000,
	}).then(res => {
		if (res.bizCode === "00000") {
			model.storeList = res.data?.list || [];
			model.store = model.storeList[0] || {};
			getModel()
			getData()
		}
	})
}

const searchFocus = () => {
	// searchFocus.value = true;
	// model.showSearch = true;
}

onMounted(() => {
	getStore()
})
</script>

<style lang="less" scoped>
.page-container {
	font-size: 20rpx;
	color: #525252;
	font-weight: 400;
	line-height: 50rpx;
	background: #fff;

	.top-wrap {
		// height: 308rpx;

		.top-row {
			position: relative;
			padding: 15rpx 30rpx;
			border-bottom: 2rpx solid #D9D9D9;


			&:nth-child(1) {
				gap: 20rpx;
			}

			&:nth-child(2) {
				line-height: 39rpx;
				gap: 20rpx;
			}

			.text {
				width: 21%;
				font-size: 24rpx;
				font-weight: 500;
				color: #000;

				.name {
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					width: 95%;
				}

				&:nth-child(1),
				&:nth-child(3) {
					color: #B98A73;
				}

				&:nth-child(4) {
					width: 28%;
					transition: all 0.3s;

					&.active {
						width: 95%;
						position: absolute;
					}
				}
			}

			.tag-color {
				width: 22rpx;
				height: 22rpx;
				display: inline-block;
				margin-right: 10rpx;
				vertical-align: -4rpx;
			}
		}
	}

	.position {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: #B98A73;
		font-size: 32rpx;
		line-height: 80rpx;
		text-align: center;
		color: #000;
		position: fixed;
		bottom: 130rpx;
		right: 100rpx;
		color: #fff;
	}

	.inventory-list {
		height: calc(100vh - 350rpx);
		overflow-y: scroll;
		box-sizing: border-box;
		position: relative;


		.scroll-row {
			position: relative;

			width: max-content;

			&:first-child {
				box-shadow: 0 8rpx 12rpx rgba(0, 0, 0, 0.1);
			}
		}

		.scroll-content-row {
			position: relative;
			width: max-content;

			.fixed-left {
				border-right: 1px solid #D9D9D9;
			}

			.scroll-row {
				border-top: 1px solid #D9D9D9;
				border-bottom: 1px solid #D9D9D9;

				.scroll-item {
					border-right: 1px solid #D9D9D9;
					box-sizing: border-box;
					background: #f8fafc;
				}
			}

		}

		.list-item {
			// border-bottom: 1rpx solid #D9D9D9;
			color: #000;

			.model-name {
				padding: 20rpx 32rpx;
				font-size: 24rpx;
				position: sticky;
				left: 0;
				top: 0;
				width: 91vw;
				overflow: hidden;
			}

			button {
				width: 120rpx !important;
				margin: 0;
			}
		}

		.fixed-left {
			flex-shrink: 0;
			position: sticky;
			left: 0;
			background: #fff;
			padding: 0 30rpx;
			height: 80rpx;
			line-height: 80rpx;
			z-index: 5;
		}

		.scroll-list {
			// margin-left: 160rpx;
			height: 80rpx;
			line-height: 80rpx;
			position: relative;

			.scroll-block {
				height: 100%;
				position: absolute;
				top: 0;
			}
		}

		.scroll-item {
			display: inline-block;
			text-align: center;
			width: 110rpx;
			height: 100%;
		}
	}

	.bg-1 {
		background: #FEDFCC;
	}

	.bg-2 {
		background: #D6DCFB;
	}

	.bg-3 {
		background-image: repeating-linear-gradient(-45deg, #FFDDC3, #ffffff 3px, #FFDDC3 3px, #fff 3px);
	}

	.bg-4 {
		background: #FB9791;
	}
}

.close-popup-content {
	color: #000;

	.vehicle-info {
		font-size: 20rpx;
		margin: 10rpx 0 20rpx;
	}

	.title {
		font-size: 32rpx;
		font-weight: 600;
	}

	.popup-btn-group {
		margin-top: 80rpx;

		button {
			width: 130px !important;
			margin: 0;
			border: none !important;
			border-color: transparent !important;

			&:nth-child(1) {
				color: #000;
			}
		}
	}
}
</style>